package com.dubbo.auth.shiro;

import com.dubbo.auth.exception.AuthException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Service
public class DefaultAuthLoginService implements AuthLoginService {

    @Override
    public DefaultAuthUserInfo getAuthUserInfoByName(String name) {
        DefaultAuthUserInfo defaultAuthUserInfo = new DefaultAuthUserInfo();
        defaultAuthUserInfo.setName("yang");
        defaultAuthUserInfo.setPassword("123456");
        Set<String> role = new HashSet<>();
        defaultAuthUserInfo.setRole(role);
        Set<String> permission = new HashSet<>();
        defaultAuthUserInfo.setPermission(permission);
        return defaultAuthUserInfo;
    }

    @Override
    public void login(AuthUserInfo authUserInfo) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                authUserInfo.getName(),
                authUserInfo.getPassword()
        );
        try {
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
             throw new AuthException("用户不存在");
        } catch (AuthenticationException e) {
            throw new AuthException("账号或者密码错误");
        } catch (AuthorizationException e) {
            throw new AuthException("用户权限不存在");
        }
    }

}
